package online.flowerinsnow.minecraft.bukkit.manhunt.manager.impl;

import org.bukkit.*;
import online.flowerinsnow.minecraft.bukkit.manhunt.manager.IWorldManager;
import online.flowerinsnow.minecraft.bukkit.manhunt.runnable.DeleteFileRunnable;

import java.io.File;

public class WorldManagerImpl implements IWorldManager {
    @Override
    public World createArena() {
        createWorld("nether", World.Environment.NETHER);
        createWorld("theend", World.Environment.THE_END);
        return createWorld("arena", World.Environment.NORMAL);
    }

    @Override
    public World getArena() {
        return Bukkit.getWorld("arena");
    }

    @Override
    public void deleteArena(Runnable afterDone) {
        clearWorld("arena");
        clearWorld("nether");
        clearWorld("theend");
        Bukkit.unloadWorld("arena", false);
        Bukkit.unloadWorld("nether", false);
        Bukkit.unloadWorld("theend", false);
        new DeleteFileRunnable(new File(Bukkit.getWorldContainer(), "arena"), () ->
                new DeleteFileRunnable(new File(Bukkit.getWorldContainer(), "nether"), () ->
                        new DeleteFileRunnable(new File(Bukkit.getWorldContainer(), "theend"), afterDone).start()).start()).start();


    }

    @Override
    public boolean hasArena() {
        return getArena() != null;
    }
    private World createWorld(String name, World.Environment environment) {
        World world = Bukkit.createWorld(WorldCreator.name(name)
        .environment(environment));
        //noinspection ConstantConditions
        world.setDifficulty(Difficulty.HARD);
        return world;
    }
    private void clearWorld(String name) {
        World world = Bukkit.getWorld(name);
        if (world != null) {
            //noinspection ConstantConditions
            world.getPlayers().forEach(p -> p.teleport(Bukkit.getWorld("world").getSpawnLocation()));
        }
    }
}
